package com.gzs.space.service.impl;

import com.gzs.space.entity.FdfsFile;
import com.gzs.space.mapper.UploadFileMapper;
import com.gzs.space.service.UploadFileService;
import com.gzs.space.utils.FastDFSUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author GZS
 * @date 2022年04月17日
 */
@Service
public class UploadFileServiceImpl implements UploadFileService {
	@Resource
	private UploadFileMapper uploadFileMapper;

	@Override
	public boolean uploadFile(MultipartFile file) {
		try {
			String[] result = FastDFSUtils.upload(file.getInputStream(),
					file.getOriginalFilename());
			if (result == null){
				return false;
			}
			// System.out.println(Arrays.toString(result));
			FdfsFile fdfsFile = new FdfsFile(null,
					file.getOriginalFilename(),
					result[0],
					result[1],
					new Date());
			int insert = uploadFileMapper.insert(fdfsFile);
			// String nn = uploadFileMapper.selectA();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public List<FdfsFile> findAll() {

		return uploadFileMapper.findAll();
	}

	@Override
	public boolean deleteFile(Integer id) {
		try {
			FdfsFile fdfsFile = uploadFileMapper.findById(id);
			boolean isDelete = FastDFSUtils.delete(fdfsFile.getGroupName(),fdfsFile.getNewFileName());
			boolean flag = uploadFileMapper.deleteFile(id);
			if (flag && isDelete){
				return true;
			}else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	@Override
	public void downLoad(Integer id, HttpServletResponse response) {
		try {
			FdfsFile fdfsFile = uploadFileMapper.findById(id);
			byte[] tmp = FastDFSUtils.downLoad(fdfsFile.getGroupName(), fdfsFile.getNewFileName());
			if (tmp == null){
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().println("<h3>服务器正忙，请稍后重试<h3>");
				response.getWriter().flush();
				return;
			}
			//下载成功，吧从fastdfs中下载的字节数组，写到客户端
			//设置响应头 mime-type，octet-stream:全适配，代表流
			response.setContentType("application/octet-stream");
			//设置附件名称
			response.setHeader("content-disposition",
					"attachment;filename="+fdfsFile.getFileName());
			//输出文件内容到客户端
			response.getOutputStream().write(tmp,0,tmp.length);
			response.getOutputStream().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
